import { Popup, Picker } from "vant";
// import Hybrid from "@/components/uzone-hybrid";
import keyMap from "@/config/key-map";
import { validateCompanyPhone, validateAddress } from "@/libs/validate";
// import ubt from "@/service/ubt";
import MixinValidateForm from "@/service/mixin-validate-form";
import NavBar from "../components/navBar1";
import Region from "../../../../static/region.json";
import Province from "../../../../static/province.json";
import City from "../../../../static/city.json";
import doFaceButton from "@/components/doFaceButton";

export default {
  name: "work-information",
  components: {
    NavBar,
    Popup,
    Picker,
    doFaceButton,
  },
  mixins: [MixinValidateForm],
  data() {
    return {
      productId: "",
      readonly: false,
      instalment: false,
      form: {
        region: "", // 地区
        province: "", // 省
        city: "", // 城市
        address: "", // 详细地址
        companyName: "", // 公司名称
        jobType: "", // 职业
        jobTypeId: "", // 职业id
        // position: '', // 职位
        payCycle: "", // 发薪周期
        payday: ["", ""],
        payday1: "", // 发薪日
        payday2: "", // 发薪日
        salary: "", // 月收入
        companyTel: "", // 公司电话
      },
      status: {
        identity: null,
        personal: null,
        work: null,
        contact: null,
        additional: null,
      },
      regionData: [],
      provinceData: [],
      cityData: [],
      professionData: keyMap.profession,
      positionData: keyMap.position,
      payrollCycleData: keyMap.payrollCycle,
      paydayData: keyMap.payday,
      paydayWeekData: keyMap.paydayWeek,
      incomeData: keyMap.income,
      isVisibleChooseRegion: false,
      isVisibleChooseRegionP: false,
      isVisibleChooseProvince: false,
      isVisibleChooseProvinceP: false,
      isVisibleChooseCity: false,
      isVisibleChooseCityP: false,
      isVisibleChooseProfession: false,
      isVisibleChooseProfessionP: false,
      isVisibleChoosePosition: false,
      isVisibleChoosePositionP: false,
      isVisibleChoosePayrollCycle: false,
      isVisibleChoosePayrollCycleP: false,
      isVisibleChoosePayday: false,
      isVisibleChoosePaydayP: false,
      isVisibleChoosePaydayWeek: false,
      isVisibleChoosePaydayWeekP: false,
      isVisibleChooseIncome: false,
      isVisibleChooseIncomeP: false,
      paydayIndex: null,
      btnName: this.$t("next"),
      disabledBtn: false,
      pageTrackerInfo: {
        page: 'workInfo',
        startTime: new Date().getTime()
      }
    };
  },
  computed: {
    isOptional() {
      const id = this.form.jobTypeId;
      return (
        id === "33" ||
        id === "34" ||
        id === "35" ||
        id === "36" ||
        id === "37" ||
        id === "38" ||
        id === "39"
      );
    },
    isStudent() {
      const id = this.form.jobTypeId;
      return id === "35";
    },
    btnCanSubmit() {
      // const id = this.form.jobTypeId;
      // const isOptional = (id === '33' || id === '34' || id === '36' || id === '37' || id === '38' || id === '39');
      // const isStudent = (id === '35');
      // const { region, province, city, address, companyName, position, payCycle, companyTel, payday1, payday2, salary } = this.form;
      // return (
      //   !isOptional &&
      //   !isStudent &&
      //   (!region || !province || !city || !address || !companyName || !companyTel || !salary ||
      //     (!position || !payCycle ||
      //       (payCycle === 'Weekly' && !payday1) ||
      //       (payCycle === 'Once two weeks' &&
      //         (!payday1 || !payday2)) ||
      //       (payCycle === 'Monthly' && !payday1)
      //     )
      //   )
      // ) || (isOptional && !salary);

      const {
        region,
        province,
        city,
        address,
        companyName,
        // position,
        companyTel,
        salary,
      } = this.form;
      return (
        !region ||
        !province ||
        !city ||
        !address ||
        !companyName ||
        !companyTel ||
        !salary
      );
    },
  },
  watch: {
    "form.payCycle": function (newVal, oldVal) {
      if (oldVal != "" && oldVal !== newVal) {
        this.form.payday = ["", ""];
        this.form.payday1 = "";
        this.form.payday2 = "";
      }
    },
  },
  methods: {
    /**
     * 获取省数据
     */
    getProvinceData() {
      const region = this.form.region;
      const regionObj = Region.region.filter((item) => item.region === region);
      if (regionObj && regionObj.length >= 1) {
        const regionId = regionObj[0].RegionId;
        this.provinceData = Province.province.filter(
          (item) => item.RegionId === regionId
        );
      }
    },
    /**
     * 获取城市数据
     */
    getCityData() {
      // const region = this.form.region;
      const province = this.form.province;
      const provinceObj = Province.province.filter(
        (item) => item.Province === province
      );
      const provinceId = provinceObj[0].ProvinceId;
      this.cityData = City.city.filter(
        (item) => item.ProvinceId === provinceId
      );
    },
    /**
     * 显示地区选择框
     */
    showChooseRegion() {
      this.isVisibleChooseRegionP = true;
      setTimeout(() => {
        this.isVisibleChooseRegion = true;
      }, 100);
    },
    /**
     * 显示省选择框
     */
    showChooseProvince() {
      this.isVisibleChooseProvinceP = true;
      setTimeout(() => {
        this.isVisibleChooseProvince = true;
      }, 100);
    },
    /**
     * 显示城市选择框
     */
    showChooseCity() {
      this.isVisibleChooseCityP = true;
      setTimeout(() => {
        this.isVisibleChooseCity = true;
      }, 100);
    },
    /**
     * 选择地区
     */
    chooseRegion(val) {
      const form = this.form;
      if (form.region !== val.region) {
        form.region = val.region;
        form.province = "";
        form.city = "";
        this.getProvinceData();
        this.showChooseProvince();
      }
      this.isVisibleChooseRegion = false;
      this.isVisibleChooseRegionP = false;
    },
    /**
     * 选择省
     */
    chooseProvince(val) {
      const form = this.form;
      if (form.province !== val.Province) {
        form.province = val.Province;
        form.city = "";
        this.getCityData();
        this.showChooseCity();
      }
      this.isVisibleChooseProvince = false;
      this.isVisibleChooseProvinceP = false;
    },
    /**
     * 选择城市
     */
    chooseCity(val) {
      this.form.city = val.TownCity;
      this.isVisibleChooseCity = false;
      this.isVisibleChooseCityP = false;
    },
    /**
     * 显示职业选择框
     */
    showChooseProfession() {
      this.isVisibleChooseProfessionP = true;
      setTimeout(() => {
        this.isVisibleChooseProfession = true;
      }, 100);
    },
    /**
     * 选择职位职业
     */
    chooseProfession(val) {
      this.form.jobType = val.name;
      this.form.jobTypeId = val.id;
      this.isVisibleChooseProfession = false;
      this.isVisibleChooseProfessionP = false;
    },
    /**
     * 显示职位选择框
     */
    showChoosePosition() {
      this.isVisibleChoosePositionP = true;
      setTimeout(() => {
        this.isVisibleChoosePosition = true;
      }, 100);
    },
    /**
     * 选择职位
     */
    choosePosition(val) {
      this.form.position = val;
      this.isVisibleChoosePosition = false;
      this.isVisibleChoosePositionP = false;
    },
    /**
     * 显示发薪周期选择框
     */
    showChoosePayrollCycle() {
      this.isVisibleChoosePayrollCycleP = true;
      setTimeout(() => {
        this.isVisibleChoosePayrollCycle = true;
      }, 100);
    },
    /**
     * 选择发薪周期
     */
    choosePayrollCycle(val) {
      this.form.payCycle = val;
      this.isVisibleChoosePayrollCycle = false;
      this.isVisibleChoosePayrollCycleP = false;
    },
    /**
     * 显示发薪日选择框
     */
    showChoosePayday(index) {
      if (this.form.payCycle !== "Weekly") {
        this.paydayIndex = index;
        this.isVisibleChoosePaydayP = true;
        setTimeout(() => {
          this.isVisibleChoosePayday = true;
        }, 100);
      }
      if (this.form.payCycle === "Weekly") {
        this.isVisibleChoosePaydayWeekP = true;
        setTimeout(() => {
          this.isVisibleChoosePaydayWeek = true;
        }, 100);
      }
    },
    /**
     * 选择发薪日
     */
    choosePayday(val) {
      this.form["payday" + this.paydayIndex] = val;
      this.form.payday.splice(this.paydayIndex - 1, 1, val);
      this.isVisibleChoosePayday = false;
      this.isVisibleChoosePaydayP = false;
    },
    /**
     * 选择周薪发薪日
     */
    choosePaydayWeek(val) {
      this.form.payday1 = val;
      this.form.payday[0] = val;
      this.isVisibleChoosePaydayWeek = false;
      this.isVisibleChoosePaydayWeekP = false;
    },
    /**
     * 显示选择月收入
     */
    showChooseIncome() {
      this.isVisibleChooseIncomeP = true;
      setTimeout(() => {
        this.isVisibleChooseIncome = true;
      }, 100);
    },
    /**
     * 选择月收入
     */
    chooseIncome(val) {
      this.form.salary = val;
      this.isVisibleChooseIncome = false;
      this.isVisibleChooseIncomeP = false;
    },
    /**
     * 获取页面数据
     */
    getData() {
      this.$api.queryUserJobInfo().then((res) => {
        const { status, error, data } = res;
        console.warn(data);
        if (
          "1" === status &&
          ("00000000" === error || "0000" === error) &&
          data
        ) {
          const form = this.form;

          // form.jobType = data.jobType;
          // if (form.jobType) {
          //   const jobType = this.professionData.filter(item => item.name === form.jobType);
          //   form.jobTypeId = jobType[0].id;
          // }

          form.region = data.district;
          form.province = data.province;
          form.city = data.city;
          if (form.region) {
            this.getProvinceData();
            this.getCityData();
          }
          form.address = data.address;
          form.companyName = data.companyName;
          form.position = data.position;
          // form.payCycle = data.payCycle;
          form.salary = data.salary;
          form.companyTel = data.companyTel;
          // if (data.payDay) {
          //   const payDay = data.payDay.split(',');
          //   form.payday = data.payDay ? payDay : ['', ''];
          //   form.payday1 = payDay[0] ? payDay[0] : '';
          //   form.payday2 = payDay[1] ? payDay[1] : '';
          // }
        }
      });
    },
    /**
     * 获取资料填写度
     */
    getInfoData() {
      this.$api.getDataIntegrity().then((res) => {
        const { status, error, data } = res;
        if (
          "1" === status &&
          ("00000000" === error || "0000" === error) &&
          data
        ) {
          const status = this.status;
          status.identity = data.USERBASEINFO === "1"; // 基本信息
          status.personal = data.USERPERSONALINFO === "1"; // 个人信息
          status.work = data.USERJOB === "1"; // 工作信息
          status.contact = data.USERCONTACT === "1"; // 联系人信息
          status.additional = data.USERCARDID === "1"; // 身份信息
          if (data.USERJOB === "1") {
            this.readonly = true;
          }
        }
      });
    },
    /**
     * 跳转填资
     */
    goInformation(url) {
      const path = "/information/" + url;
      const instalment = this.instalment ? "true" : "false";
      this.$router.push({
        path,
        query: { productId: this.productId, instalment },
      });
    },
    /**
     * 表单提交
     */
    submitHandler() {
      if (this.disabledBtn) return
      // 工作信息页 - 提交 - 点击
      this.$buryPoint.action({
        eventName: 'workInfo_submit_click',
        ...this.pageTrackerInfo
      });

      const form = this.form;
      if (!this.checkInput("workForm")) {
        this.$toast("Please complete your information");
        return;
      }
      if (form.payday1 && form.payday2 && form.payday1 === form.payday2) {
        this.$toast(this.$tc("paydayCanNotSame"));
        return;
      }
      if (form.companyTel && !validateCompanyPhone(form.companyTel)) {
        //this.$toast(this.$tc("plsInputRightCompany"));
        this.markInputNew(["companyTel"]);
        return;
      } else {
        this.removeMarkClick(["companyTel"]);
      }
      if (!validateAddress(form.address)) {
        //this.$toast(this.$tc("plsInputCorrectAddress"));
        this.markInputNew(["address"]);
        return;
      } else {
        this.removeMarkClick(["address"]);
      }
      const params = {
        district: form.region, // 大区
        province: form.province, // 省
        city: form.city, // 市

        // jobType: form.jobType, // 职业
        // jobType: this.professionData[0].name, // 职业

        // position: form.position, // 职位
        companyName: form.companyName, // 公司名称
        address: form.address, // 详细地址

        payCycle: form.payCycle, // 发薪周期
        // payCycle: this.payrollCycleData[0],

        companyTel: form.companyTel, // 公司电话

        payDay: form.payCycle !== "Daily" ? form.payday.join(",") : "-1",
        // payDay: this.paydayData[0],

        salary: form.salary,
      };
      this.disabledBtn = true;
      this.$api
        .addOrUpdateUserJobInfo(params)
        .then((res) => {
          const { status, error, msg } = res;
          if ("1" === status && ("00000000" === error || "0000" === error)) {
            // 工作信息页 - 提交 - 成功
            this.$buryPoint.action({
              eventName: 'workInfo_submit_success',
              ...this.pageTrackerInfo
            });
            this.$refs.checkFaceInfo.returnTo().catch(e => {
              this.disabledBtn = false;
            });
          } else {
            this.disabledBtn = false
            this.$toast(msg);
          }
        })
        .catch((error) => {
          this.disabledBtn = false;
        });
    },
    // 聚焦
    IdFocus(e) {
      // const params = {
      //   content: 'job_page_company_tel_fill_start',
      //   value: '',
      // };
      // this.$hybrid.action('ee', {
      //   ...params
      // });
    },
    // 取消聚焦
    IdBlur(e) {
      // const params = {
      //   content: 'job_page_company_tel_fill_end',
      //   value: e.target.value,
      // };
      // console.warn(params);
      // this.$hybrid.action('ee', {
      //   ...params
      // });
      const form = this.form;
      if (form.companyTel && !validateCompanyPhone(form.companyTel)) {
        // this.$toast(this.$tc("plsInputRightCompany"));
        this.markInputNew(["companyTel"]);
        return;
      } else {
        this.removeMarkClick(["companyTel"]);
      }
      const dom = e.target;
      const val = form.companyTel;
      if (!val) {
        this.markEle(dom);
      }
    },
    handleBlurCheck(e, type = "") {
      //  校验规则提前
      const dom = e.target;
      if (type === "address") {
        if (!validateAddress(dom.value)) {
          //this.$toast(this.$tc("plsInputCorrectAddress"));
          this.markInputNew(["address"]);
          return;
        } else {
          this.removeMarkClick(["address"]);
        }
      }
      setTimeout(() => {
        const val = dom.value;
        if (!val) {
          this.markEle(dom);
        }
      }, 0);
    },
  },
  created() {
    const query = this.$route.query;
    this.productId = query.productId;
    if (query.btnType && query.btnType === "save") {
      // 按钮是下一步，还是保存
      this.btnName = this.$t("save");
    }
    // this.readonly = (query.readonly === 'true');
    this.instalment = query.instalment === "true";
    this.regionData = Region.region;
    this.getInfoData();
    this.getData();
  },
  beforeDestroy () {
    this.pageEndAction()
  },
  mounted () {
    this.pageStartAction()
    this.$buryPoint.action({
      eventName: 'workInfo_page_show',
      ...this.pageTrackerInfo
    });
  }
};
